package cn.rebeater.navigationclient.ui.home;

import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.os.Message;
import android.util.Log;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.UUID;

class BluetoothMsgType {
    final static int msgdata = 1;
    final static int msgerror = 2;
    final static int msginterrupt = 3;
}

public class BluetoothThread extends Thread {

    private ActivityHandler mhandler = null;
    private BluetoothSocket mbtsocket = null;
    private BufferedReader mbtread = null;
    private BufferedWriter mbwrite = null;
    private boolean endthread = false;
    private String TAG = "mydebug";
    FileOutputStream fileOutputStream;
    BufferedOutputStream bufferedOutputStream;
    BufferedWriter bufferedWriter = null;
    private static final UUID muuid = UUID.fromString
            ("00001101-0000-1000-8000-00805F9B34FB");


    BluetoothThread(BluetoothDevice device, ActivityHandler
            handler, String logFileName) {
        mhandler = handler;

       /* File f = new File(logFileName);
        if (!f.exists()) {
            try {
                boolean res = f.createNewFile();
                if(!res){
                    Log.i("mydebug", "BluetoothThread: log file create failed");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            //打开文件
            bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(logFileName));
            bufferedOutputStream.write(("file: " + logFileName).getBytes());
            bufferedOutputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (bufferedWriter != null) {
                    bufferedWriter.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }*/


        try {
            mbtsocket = device.createRfcommSocketToServiceRecord(muuid);
            mbtsocket.connect();
            mbtread = new BufferedReader(new InputStreamReader(mbtsocket
                    .getInputStream()));
            mbwrite = new BufferedWriter(new OutputStreamWriter(mbtsocket.getOutputStream()));

        } catch (Exception e) {
            endthread = true;
            sendMessageToUi(BluetoothMsgType.msgerror, "");
            e.printStackTrace();
        }
    }

    /**
     * 发送数据到UI线程
     *
     * @param msgtype 命令字
     * @param str     字符消息
     */
    private void sendMessageToUi(int msgtype, String str) {
        Message msg = new Message();
        msg.arg1 = msgtype;
        msg.obj = str;
        mhandler.sendMessage(msg);
    }

    public void sendCommand(final String cmd) {
        new Thread() {
            @Override
            public void run() {
                super.run();
                try {
                    mbwrite.write(cmd);
                    mbwrite.flush();
                } catch (Exception e
                ) {
                    e.printStackTrace();
                }
            }
        }.start();

    }

    void onDestroy() {
        try {
            if (bufferedWriter != null) {
                bufferedWriter.close();
            }
            if (bufferedOutputStream != null) {
                bufferedOutputStream.close();
            }
            if (fileOutputStream != null) {
                fileOutputStream.close();
            }
            // 先关闭套接字
            if (mbtsocket != null) {
                mbtsocket.close();
                mbtsocket = null;
            }

            // 再关闭输入输出
            if (mbtread != null) {
                mbtread.close();
                mbtread = null;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void checkData(String data) {
        sendMessageToUi(BluetoothMsgType.msgdata, data);
    }

    @Override
    public void run() {
        String revbuff;

        while (!endthread) {

            try {
                revbuff = mbtread.readLine();
                Log.i("mydebug", "run: " + revbuff);
//                checkData(revbuff);
       /*         bufferedOutputStream.write((revbuff + "\n").getBytes());
                bufferedOutputStream.flush();*/
            } catch (Exception e) {
                sendMessageToUi(BluetoothMsgType.msginterrupt, "");
                e.printStackTrace();
                break;
            }
            if (revbuff.length() > 0) {
                checkData(revbuff);
            }
        }
        onDestroy();
    }
}
